from common.basic_mongo import get_mongo_collection
from common.basic_rabbitmq import RabbitMQConfig
from common.basic_redis import redis_async_connect
from device_status_mgm.device_status_constant import (DB_DEVICE_ALARM_DOCUMENT,
                                                      DB_DEVICE_HEARTBEAT_DOCUMENT)
from device_status_mgm.config import ConfigStore, RedisConfigBasic
from mg_app_framework import (IdiServerConfigBasic, InitFuncBasic, app_start, get_organization,
                              set_config_func, set_init_task, set_store)
from mg_app_framework.components import TASKS, TaskKey


async def config_process():
    pass


class InitFuncConfig(InitFuncBasic):
    async def init_func(self):
        await self.create_index()

    @classmethod
    async def create_index(cls):
        # 设备报警信息
        log_collection = get_mongo_collection(
            collection_name="access_log",
            database_name=f"idi_{get_organization()}_upper_pc",
        )
        await log_collection.create_index([("trace_id", -1)], background=True)
        await log_collection.create_index([("call_id", 1), ("time", -1)], background=True)
        # await log_collection.create_index(
        #     [("time", -1)], expireAfterSeconds=3600 * 24 * 14, background=True
        # )  # 保留20天

        # 设备心跳信息
        heartbeat_handler = get_mongo_collection(
            collection_name=DB_DEVICE_HEARTBEAT_DOCUMENT,
            database_name=f"idi_{get_organization()}_upper_pc",
        )
        await heartbeat_handler.create_index(
            [("process_code", 1), ("timestamp", -1)], background=True
        )
        await heartbeat_handler.create_index(
            [("timestamp", -1)], expireAfterSeconds=3600 * 24 * 14, background=True
        )  # 保留14天

        # 设备报警信息
        alarm_handler = get_mongo_collection(
            collection_name=DB_DEVICE_ALARM_DOCUMENT,
            database_name=f"idi_{get_organization()}_upper_pc",
        )
        await alarm_handler.create_index([("device_code", 1), ("timestamp", -1)], background=True)
        await alarm_handler.create_index(
            [("timestamp", -1)], expireAfterSeconds=3600 * 24 * 20, background=True
        )  # 保留20天


def main(debug_flag=True):
    TASKS[TaskKey.redis_async] = redis_async_connect

    import uvloop

    uvloop.install()

    set_store(ConfigStore())
    set_config_func(config_process)
    set_init_task(
        [
            {TaskKey.redis_async: RedisConfigBasic()},
            {TaskKey.idi_server: IdiServerConfigBasic()},
            {TaskKey.rabbitmq_async: RabbitMQConfig()},  # ps: 该处的rabbitmq只做发布操作, 不做订阅操作
            {TaskKey.init_func: InitFuncConfig()},
        ]
    )
    app_start(debug_flag)
